<!--
 * @Author: 曹捷
 * @Date: 2020-06-16 17:15:40
 * @LastEditors: 曹捷
 * @LastEditTime: 2020-12-20 15:40:33
 * @Description: 底部弹出滚动组件 封装
--> 
<template>
  <picker :range="pickList" :range-key="label" :value="index" @change="changeEvent" class="login-icon p-r-5">
    <view class="color-info" v-if="index ===''">
      {{placeholder}}
      <slot></slot>
    </view>
    <view v-else class="selected">
      {{pickList[index][label]}}
      <slot></slot>
    </view>
  </picker>
</template>

<script>
export default {
  props: {
    value: {
      type: [Number, String],
    },
    keyName: {
      type: String,
      default: 'id',
    },
    label: {
      type: String,
      default: 'label',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    pickList: {
      type: Array,
      default () {
        return []
      },
    },
  },
  watch: {
    value (value) {
      this.valueToIndex()
    },
    pickList: {
      handler (n, o) {
        this.valueToIndex()
      },
      deep: true,
    }
  },
  data () {
    return {
      index: '',
    }
  },
  methods: {
    valueToIndex () {
      if (this.value) {
        this.pickList.forEach((element, index) => {
          if (element[this.keyName] == this.value) {
            this.index = index
          }
        })
      } else {
        this.index = ''
      }
    },
    changeEvent (e) {
      this.index = e.detail.value
      this.$emit('input', this.pickList[this.index][this.keyName])
      let label = this.pickList[this.index][this.label]
      // console.log('changeEvent -> label', label)
      this.$emit('update:name', label)
      this.$emit('change', this.pickList[this.index][this.keyName], this.pickList[this.index])
    },
  },
  mounted () {
    this.valueToIndex()
  },
}
</script>

<style>
.selected {
  color: #000;
  white-space: nowrap;
}
</style>